package com.guigu.qingcheng.service.impl;

import com.alibaba.fastjson.JSON;
import com.guigu.qingcheng.excption.GuliException;
import com.guigu.qingcheng.pojo.TbCategory;
import com.guigu.qingcheng.pojo.TbOrderItem;
import com.guigu.qingcheng.pojo.TbSku;
import com.guigu.qingcheng.service.CartService;
import com.guigu.qingcheng.service.GoodsServiceFeign;
import com.guigu.qingcheng.service.OrderServiceFeign;
import com.guigu.qingcheng.utils.CacheKey;
import com.guigu.qingcheng.utils.IdWorker;
import com.guigu.qingcheng.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderServiceFeign orderServiceFeign;

    @Override
    public List<Map<String, Object>> findCartList(String username) {
        System.out.println(username);
        // 从redis中提取购物车
        List<Map<String, Object>> list =(List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if(list==null){
            list= new ArrayList<>();
        }
        return list;
    }

    @Override
    public void addItem(String username, String skuId, Integer num) {
        // 实现思路 遍历购物车，如果存在当前商品就修改数量，不存在就添加
        // 获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        boolean bool=false; //是否在购物车存在
        for (Map map:cartList){
           TbOrderItem orderItem=(TbOrderItem) map.get("item");
           if(orderItem.getSkuId().equals(skuId)){
                // 购物车存在该商品
               if(orderItem.getNum()<=0){
                    cartList.remove(map);
                   bool=true;
                    break;
               }
               int weight= orderItem.getWeight()/orderItem.getNum();
                orderItem.setNum(orderItem.getNum()+num);// 数量变更
                orderItem.setMoney(orderItem.getPrice()*orderItem.getNum()); //金额变更
                orderItem.setWeight(weight*orderItem.getNum()); //重量变更

               if(orderItem.getNum()<=0){
                   cartList.remove(map);
               }
               bool=true;
               break;
           }
        }
        // 如果购物车不存在该商品就添加
        if(bool==false){
            R r = goodsServiceFeign.detail(skuId);
            TbSku tbSku = JSON.parseObject(JSON.toJSONString(r.getData().get("tbSku")), TbSku.class);
//            TbSku tbSku= (TbSku)r.getData().get("tbSku");
            if(tbSku==null){
                throw new GuliException(20001,"商品不存在");
            }
            if(!"1".equals(tbSku.getStatus())){
                throw new GuliException(20001,"商品状态不合法");
            }
            if(num<=0){
                throw new GuliException(20001,"商品数量不合法");
            }

            // 封装数据
            TbOrderItem orderItem=new TbOrderItem();
            orderItem.setId(idWorker.nextId()+"");
            // 设置三级分类id
            orderItem.setCategoryId3(tbSku.getCategoryId());


            // 商品分类
            // 先到缓存查询
            TbCategory tbCategory3=(TbCategory) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(tbSku.getCategoryId());
            if(tbCategory3==null){ //如果缓存中不存在
                R detailcategory = goodsServiceFeign.detailcategory(orderItem.getCategoryId3());
                tbCategory3= JSON.parseObject(JSON.toJSONString(detailcategory.getData().get("tbCategory")), TbCategory.class);
               // tbCategory3=(TbCategory) detailcategory.getData().get("tbCategory");
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(tbSku.getCategoryId(),tbCategory3);
            }
            // 设置二级分类id
            orderItem.setCategoryId2(tbCategory3.getParentId());

            TbCategory tbCategory2=(TbCategory) redisTemplate.boundHashOps(CacheKey.CATEGORY).get(tbCategory3.getParentId());
            if(tbCategory2==null){
                R detailcategory = goodsServiceFeign.detailcategory(tbCategory3.getParentId());
                tbCategory2= JSON.parseObject(JSON.toJSONString(detailcategory.getData().get("tbCategory")), TbCategory.class);
               // tbCategory2=(TbCategory) detailcategory.getData().get("tbCategory");
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(tbCategory3.getParentId(),tbCategory2);
            }
            // 设置一级分类id
            orderItem.setCategoryId1(tbCategory2.getParentId());


            orderItem.setSkuId(tbSku.getId());
            orderItem.setSpuId(tbSku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(tbSku.getImage());
            orderItem.setPrice(tbSku.getPrice());
            orderItem.setName(tbSku.getName());
            orderItem.setMoney(orderItem.getPrice()*num); //金额计算
            if(tbSku.getWeight()==null){
                tbSku.setWeight(0);
            }
            orderItem.setWeight(tbSku.getWeight()*num); //重量计算

            Map map=new HashMap();
            map.put("item",orderItem);
            map.put("checked",true); //默认选中

            cartList.add(map);
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        // 获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        boolean blo=false;
        for (Map map:cartList){
           TbOrderItem orderItem =(TbOrderItem)map.get("item");
            if(orderItem.getSkuId().equals(skuId)){
                map.put("checked",checked);
                blo=true;
                break;
            }
        }
        if(blo){
            // 更新缓存
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        }
        return blo;
    }

    @Override
    public void deleteCheckedCart(String username) {
        // 获取未选中购物车
        List<Map<String, Object>> cartList = findCartList(username).stream().filter(cart ->(boolean)cart.get("checked")==false)
                .collect(Collectors.toList());
        // 更新缓存
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public int preferential(String username) {
        // 获取选中的购物车
        List<TbOrderItem> tbOrderItems = findCartList(username).stream().filter(cart -> (boolean) cart.get("checked") == true)
                .map(cart -> (TbOrderItem) cart.get("item"))
                .collect(Collectors.toList());

        // 按分类统计每个分类的金额
        Map<Integer, IntSummaryStatistics> collect = tbOrderItems.stream().collect(Collectors.groupingBy(TbOrderItem::getCategoryId3, Collectors.summarizingInt(TbOrderItem::getMoney)));

        // 循环结果，统计每个分类的优惠金额，并累加
        int totalMoney=0;
        for (Integer categoryId:collect.keySet()){
            // 获取品类的消费金额
            int money = (int)collect.get(categoryId).getSum();
            R r = orderServiceFeign.findPreMoneyByCategoryId(categoryId, money);
           int preMoney=(int) r.getData().get("payMoney");
            totalMoney+=preMoney;
        }
        return totalMoney;
    }

    @Override
    public List<Map<String, Object>> findNewCartList(String username) {
        // 获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        // 循环购物车
        for (Map map:cartList){
            TbOrderItem orderItem =(TbOrderItem)map.get("item");
            R r = goodsServiceFeign.detail(orderItem.getSkuId());
            TbSku tbSku = JSON.parseObject(JSON.toJSONString(r.getData().get("tbSku")), TbSku.class);
            orderItem.setPrice(tbSku.getPrice()); //更新价格
            orderItem.setMoney(tbSku.getPrice()*orderItem.getNum()); // 更新金额
        }
        // 保存购物车
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        return cartList;
    }
}
